package com.ht.api.call.impl;

import java.util.List;

import javax.sql.DataSource;

import com.ht.api.db.*;
import org.springframework.stereotype.Component;

import com.ht.api.bean.AjaxResult;
import com.ht.api.bean.LoginBean;
import com.ht.api.call.AbstractCall;
import com.ht.api.db.exception.HtException;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

/**
 * 业务执行器:del
 * @author asq
 * @createTime 2024年12月23日 21:02:18
 */
@Component
public class DelCall extends AbstractCall {
	
	@Override
	public boolean isOpen() {
		return false;
	}

	@Override
	public String getName() {
		return "通用删除";
	}

	@Override
	public AjaxResult doExecute(LoginBean me, JSONObject param, JSONObject config) {

		DataSource ds = null;
		if (me.isSysCommonCall()) {
			ds = DbConfig.useSysDb();
		} else {
			ds = me.getDataSource();
		}


		String table = config.getStr("table");
		
		Object paramObj = param.get(PARAM);
		if (paramObj instanceof JSONArray) {
			// 根据main_id数组进行批量删除
			List<Entity> list = JSONUtil.toList((JSONArray)paramObj, Entity.class);
			list.stream().forEach(b -> {
				if (!b.containsKey("main_id")) {
					throw new HtException("删除操作必须提供main_id字段~");
				}
				b.setTable(table).set("sys_deleted", 0).set("table", table);
			});
			Db.insertBatch(ds, list, false);
		} else {
			Entity entity = param.getBean(PARAM, Entity.class);
			if (entity.containsKey("where")) {
				// 按条件批量删除
				SqlParser sql = param.getBean(PARAM, SqlParser.class).setTable(table);
				DbList dbList = sql.query(ds);
				dbList.stream().forEach(b -> {
					b.setTable(table).set("sys_deleted", 0).set("table", table);
				});
				Db.insertBatch(ds, dbList, false);
			} else {
				// 按main_id删除
				doDelete(ds, entity, table);
			}
		}
		
		return AjaxResult.success();
	}
	
	/**
	 * 将一条数据标记为删除
	 * @param ds
	 * @param entity
	 * @param table
	 */
	private void doDelete(DataSource ds, Entity entity, String table) {
		entity.setTable(table).set("sys_deleted", 0).set("table", table);
		if (!entity.containsKey("main_id")) {
			throw new HtException("删除操作必须提供main_id字段~");
		}
		Db.insert(ds, entity);
	}
}
